package com.springchang.leetcode;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 */
class Solution14 {
    public String longestCommonPrefix(String[] strs) {
        //对特殊情况数据的处理
        if(strs.length == 0) {
            return "";
        }
        if(strs.length == 1) {
            return strs[0];
        }

        String result = "";

        //拿到数组的第一个字符串
        String firstStr = strs[0];
        for (int i = 1; i <= firstStr.length(); i++) {
            //获取第一个字符串的前缀
            String prefix = firstStr.substring(0, i);

            //遍历剩余的字符串，看看是否都是以这个字符串前端开头
            int count = 0;
            for (int j = 1; j < strs.length; j++) {
                if (strs[j].startsWith(prefix)) {
                    count++;
                }
            }

            if (count == strs.length - 1) {
                result = prefix;
            } else {
                break;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Solution14 solution = new Solution14();
        System.out.println(solution.longestCommonPrefix(new String[]{"flower","flow","flight"}));
        System.out.println(solution.longestCommonPrefix(new String[]{"dog","racecar","car"}));
        System.out.println(solution.longestCommonPrefix(new String[]{"c"}));
    }
}
